﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.Receives;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using SqlSugar;
using System.Security.Claims;
using static Dapper.SqlMapper;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.ReturnMonerys.Receives
{
    public class ReceiveAddCommandHandler : IRequestHandler<ReceiveAddCommand, ApiResult<bool>>
    {
        private readonly SqlsugarDb<Receive> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;

        public ReceiveAddCommandHandler(IMapper mapper, SqlsugarDb<Receive> db, IHttpContextAccessor httpContextAccessor)
        {

            this.mapper = mapper;
            this.db = db;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<ApiResult<bool>> Handle(ReceiveAddCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<bool>();
            try
            {
                if (request.IsInvoice == 1 || request.IsInvoice == 2)
                {
                    var Receives = mapper.Map<Receive>(request);
                    Receives.IsDelete = false;
                    Receives.CreateTime = DateTime.Now;
                    Receives.CreateName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                    Receives.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);

                    var updataResult = await db.AddAsync(Receives);

                    if (updataResult > 0)
                    {
                        result.data = true;
                        result.Code = Enumcode.ok;
                        result.message = "收款信息添加成功";
                    }
                    else
                    {
                        result.data = false;
                        result.Code = Enumcode.fail;
                        result.message = "收款信息修改失败";

                    }
                }
                else
                {
                    result.message = "输入数据不合法";
                    result.Code = Enumcode.Errordata;
                    result.data = false;
                    return result;
                }
                  
               
               
            }
            catch (Exception ex)
            {

                result.data = false;
                result.Code = Enumcode.fail;
                result.message =ex.Message;
            }
          
            return await Task.FromResult(result);
            
        }
    }
}
